package com.cqrt.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.common.base.Strings;
import com.cqrt.config.CustomObjectMapper;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.constant.RTPlmConstant;
import com.cqrt.dto.CheckTableDTO;
import com.cqrt.dto.IssueDTO;
import com.cqrt.dto.MaterialDTO;
import com.cqrt.dto.RTImportTaskDTO;
import com.cqrt.dto.RiskDTO;
import com.cqrt.entity.RTPrjTaskJobLinkDO;
import com.cqrt.entity.RtTemporaryTask;
import com.cqrt.mapper.RTOutRuleMapper;
import com.cqrt.mapper.RTProjectMapper;
import com.cqrt.mapper.RTTaskMapper;
import com.cqrt.service.RTTaskService;
import com.cqrt.service.RtTemporaryTaskService;
import com.cqrt.service.RtWorkItemService;
import com.cqrt.util.DateUtils;
import com.cqrt.util.ExcelDateConverterUtil;
import com.cqrt.util.WorkdayCalculator;
import com.cqrt.vo.RTCheckTableVO;
import com.cqrt.vo.RTTaskVO;
import com.cqrt.vo.SubJobVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.basic.vo.cad.CadDownloadFileVO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchTypeDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.core.context.TyppmUser;
import com.hustcad.plm.pdm.core.handle.exception.SystemErrorCodeEnum;
import com.hustcad.plm.pdm.file.model.dto.DownloadFileDTO;
import com.hustcad.plm.pdm.file.model.vo.DownLoadFile.DownLoadFileVO;
import com.hustcad.plm.pdm.file.service.TyplmFileHandleService;
import com.hustcad.plm.pdm.file.service.upload.TyplmFileTransferService;
import com.hustcad.plm.pdm.file.util.TyplmDownloadToolUtil;
import com.hustcad.plm.pdm.filevault.model.vo.FileDataVO;
import com.hustcad.plm.pdm.filevault.service.TyplmContentDataService;
import com.hustcad.plm.pdm.filevault.service.TyplmContentReferenceLinkService;
import com.hustcad.plm.pdm.filevault.service.TyplmEncryptService;
import com.hustcad.plm.pdm.iba.model.dto.SaveObjIBADTO;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.hustcad.plm.pdm.user.service.TyplmUserService;
import com.hustcad.plm.rpm.entityconvert.BaseConvert;
import com.hustcad.plm.rpm.model.dto.admin.TyppmProjectDTO;
import com.hustcad.plm.rpm.model.dto.job.BatchJobDTO;
import com.hustcad.plm.rpm.model.dto.job.JobRemoteDTO;
import com.hustcad.plm.rpm.model.dto.job.JobStatusUpdateDTO;
import com.hustcad.plm.rpm.model.dto.job.JobTreeQueryDTO;
import com.hustcad.plm.rpm.model.dto.job.TyppmJobDTO;
import com.hustcad.plm.rpm.model.dto.outrule.TyppmOutRuleDTO;
import com.hustcad.plm.rpm.model.dto.remote.BatchInsertDocVO;
import com.hustcad.plm.rpm.model.dto.remote.DeliverRemoteDTO;
import com.hustcad.plm.rpm.model.dto.remote.DocDetailsVO;
import com.hustcad.plm.rpm.model.dto.remote.RemoteObjDTO;
import com.hustcad.plm.rpm.model.entity.job.TyppmCheckItem;
import com.hustcad.plm.rpm.model.entity.outrule.TyppmOutRuleItem;
import com.hustcad.plm.rpm.model.entity.plan.TyppmPlan;
import com.hustcad.plm.rpm.model.entity.user.TyppmUserEx;
import com.hustcad.plm.rpm.model.vo.job.JobExtVO;
import com.hustcad.plm.rpm.model.vo.job.TyppmJobVO;
import com.hustcad.plm.rpm.model.vo.meta.EnumerationItemTreeVO;
import com.hustcad.plm.rpm.model.vo.outrule.OutRuleItemVO;
import com.hustcad.plm.rpm.model.vo.outrule.OutRuleParamVO;
import com.hustcad.plm.rpm.model.vo.outrule.OutRuleVO;
import com.hustcad.plm.rpm.project.service.TyppmProjectService;
import com.hustcad.plm.rpm.service.job.TyppmJobService;
import com.hustcad.plm.rpm.service.outrule.TyppmOutRuleService;
import com.hustcad.plm.rpm.service.remote.TyppmRemotePdmService;
import com.hustcad.plm.rpm.service.resource.TyppmPlanResourceService;
import com.hustcad.plm.rpm.util.beanmapper.BeanMapper;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.dto.constraint.IbaDTO;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.local.LocalePropertyValueDO;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.response.ResponseResult;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.utils.excel.converter.ExcelToList;
import com.ty.ppm.api.service.outrule.OutRuleItemService;
import com.ty.ppm.api.service.outrule.OutRuleService;
import com.ty.ppm.model.dto.outrule.OutRuleItemDTO;
import com.ty.ppm.model.entity.outrule.OutRule;
import com.ty.ppm.model.entity.outrule.OutRuleItem;
import com.ty.ppm.model.utils.Tools;
import com.ty.security.util.TyCommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.ty.basic.utils.excel.converter.ExcelToList.getWorkbook;


@Slf4j
@Service
public class RTTaskServiceImpl implements RTTaskService {

    @Resource
    private TyppmJobService typpmJobService;
    @Resource
    private TyplmUserService typlmUserService;
    @Resource
    private TyppmPlanResourceService typpmPlanResourceService;
    @Resource
    private TyppmOutRuleService typpmOutRuleService;
    @Resource
    private RTTaskMapper rtTaskMapper;
    @Resource
    private OutRuleService outRuleService;
    @Resource
    private BaseConvert baseConvert;
    @Resource
    private OutRuleItemService outRuleItemService;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private TyppmRemotePdmService typpmRemotePdmService;
    @Resource
    private RTProjectMapper rtProjectMapper;
    @Resource
    private RTOutRuleMapper rtOutRuleMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private TyplmFileHandleService fileHandleService;
    @Resource
    private TyplmContentReferenceLinkService typlmContentReferenceLinkService;
    @Resource
    private TyplmFileTransferService typlmFileTransferService;
    @Resource
    private TyplmEncryptService typlmEncryptService;
    @Resource
    private TyplmContentDataService typlmContentDataService;
    @Resource
    private TyppmProjectService typpmProjectService;
    @Value("${rule.condition.key}")
    private String ruleConditionKey;
    @Value("${query.url}")
    private String queryConditionUrl;
    @Resource
    private RtWorkItemService workItemService;

    @Resource
    private RtTemporaryTaskService rtTemporaryTaskService;

    @Override
    @Transactional
    public List<TyppmJobDTO> batchImportTask(RTImportTaskDTO dto) {
        MultipartFile file = dto.getFile();
        //读取基础数据
        Map<String, String> materialMap = ExcelToList.getExcelPropertySettingMapByClass(MaterialDTO.class);
        Map<String, String> issueMap = ExcelToList.getExcelPropertySettingMapByClass(IssueDTO.class);
        Map<String, String> riskMap = ExcelToList.getExcelPropertySettingMapByClass(RiskDTO.class);
        Workbook workbook = getWorkbook(file);
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            for (Row row : sheet) {
                for (Cell cell : row) {
                    cell.setCellType(CellType.STRING);
                }
            }
        }
        List<MaterialDTO> materialDTOList = ExcelToList.excelToList(0, 0, workbook, MaterialDTO.class,
                                                                    materialMap);
        List<IssueDTO> issueDTOList = ExcelToList.excelToList(1, 0, workbook, IssueDTO.class,issueMap);
        List<RiskDTO> riskDTOList = ExcelToList.excelToList(2, 0, workbook, RiskDTO.class,riskMap);
        processDateFields(materialDTOList, materialMap);
        processDateFields(issueDTOList, issueMap);
        processDateFields(riskDTOList, riskMap);

        // 根据父任务
        BatchJobDTO batchJobDTO = new BatchJobDTO();
        batchJobDTO.setParentOid(dto.getJobId());
        List<TyppmJobDTO> childList = new ArrayList<>();


        for (MaterialDTO materialDTO : materialDTOList) {
            RTImportTaskDTO taskDTO = new RTImportTaskDTO();
            taskDTO.setName(materialDTO.getBomMaterialNumber() + "—" + materialDTO.getTaskName());
            taskDTO.setState("未读");
            taskDTO.setStateDisplayName("未读");
            taskDTO.setParentOTYPE(TableTypeConstrant.TY_JOB_OTYPE);
            taskDTO.setParentOID(dto.getJobId());
            taskDTO.setJobId(dto.getJobId());

            taskDTO.setProjectID(dto.getProjectID());
            taskDTO.setProjectName(dto.getProjectName());
            taskDTO.setPlanoid(dto.getPlanoid());

            taskDTO.setCreatorName(TyAccountContext.getUser().getName());
            taskDTO.setCreatorOID(TyAccountContext.getUser().getOid().toString());
            taskDTO.setCreatorDescription(TyAccountContext.getUser().getDescription());
            taskDTO.setCreatorOTYPE((TyAccountContext.getUser().getOtype()));
            UserDO userDO = typlmUserService.queryUserByName(materialDTO.getExecutor());

            taskDTO.setExecutorName(materialDTO.getExecutor());
            taskDTO.setExecutorOID(userDO.getOid().toString());
            taskDTO.setOwnerOID(userDO.getOid().toString());
            taskDTO.setOwnerOTYPE(userDO.getOtype());
            taskDTO.setExecutorOTYPE(userDO.getOtype());
            taskDTO.setExecutorDescription(userDO.getDescription());

            Map<String, Object> params = new HashMap<>();
            params.put("containeroid", dto.getProjectID());
            params.put("usertype", "USER");
            PageInfo<TyppmUserEx> result = this.typpmPlanResourceService.queryPrjTeamUserByPrjOid(params, null, null);

            result.getList().stream()
                    .filter(typpmUserEx -> typpmUserEx.getOid().equals(String.valueOf(userDO.getOid())))
                    .findFirst()
                    .ifPresent(typpmUserEx -> {
                        taskDTO.setExecutorGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setOwnerGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setExecutorGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                        taskDTO.setOwnerGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                    });

            String plannedStartTime = materialDTO.getPlannedStartTime();
            String plannedFinishTime = materialDTO.getPlannedFinishTime();
            // 处理计划日期（跳过周末）
            LocalDateTime[] processedDates = DateUtils.processPlanDates(plannedStartTime, plannedFinishTime);
            taskDTO.setStartdate(processedDates[0]);
            taskDTO.setFinishdate(processedDates[1]);
            taskDTO.setSchedule(WorkdayCalculator.calculateWorkdayDuration(
                    processedDates[0],
                    processedDates[1]
            ));

            childList.add(taskDTO);

            //  子任务继承父任务的交付规则
            params.put("jobOid", dto.getJobId());
            params.put("markfordelete", 0L);
            PageInfo<OutRule> outRulePageInfo = outRuleService.queryOutRuleByPage(params);
            if (CollUtil.isNotEmpty(outRulePageInfo.getList())) {
                List<OutRuleVO> outRules = baseConvert.copyToList(outRulePageInfo.getList(), OutRuleVO.class);
                List<TyppmOutRuleItem> outRuleItems = this.getOutRuleItemList(
                        outRules.stream().map(OutRuleVO::getOid).collect(Collectors.toList()));
                for (OutRuleVO outRule : outRules) {
                    OutRuleParamVO outRuleVO = new OutRuleParamVO();
                    List<TyppmOutRuleItem> outRuleItemList = new ArrayList<>();
                    for (TyppmOutRuleItem outRuleItem : outRuleItems) {
                        if (!outRuleItem.getOutputRuleOid().equals(outRule.getOid()))
                            continue;
                        outRuleItem.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                        outRuleItemList.add(outRuleItem);
                    }
                    outRule.setJobOid(taskDTO.getOid());
                    outRule.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                    outRuleVO.setOutRule(outRule);
                    outRuleVO.setOutRuleItemList(baseConvert.copyToList(outRuleItemList, OutRuleItemVO.class));
                    this.typpmOutRuleService.insertOutRule(outRuleVO);
                }
            }
            //增加子任务的交付物规则
            OutRuleParamVO outRuleVO = new OutRuleParamVO();
            OutRuleVO outRule = new OutRuleVO();
            outRule.setJobOid(taskDTO.getOid());

            LocalePropertyValueDO localePropertyValueDO = rtTaskMapper.selectRuleTypeByName(
                    materialDTO.getDeliverableType());

            outRule.setRuletypeOid(localePropertyValueDO.getAttributereferenceoid().toString());
            outRule.setRuletypeOtype(localePropertyValueDO.getAttributereferenceotype());
            outRule.setName(materialDTO.getTaskName());
            outRule.setCheckDelivers(1L);
            outRuleVO.setOutRule(outRule);

            List<EnumerationItemTreeVO> ruleAttributes = typpmOutRuleService.queryRuleAttributes(
                    localePropertyValueDO.getAttributereferenceoid().toString());
            Set<String> targetNames = new HashSet<>(Arrays.asList("是否必须", "立即提交", "任一提交"));

            // 过滤并转换为 Map
            Map<String, EnumerationItemTreeVO> attrMap = ruleAttributes.stream()
                    .filter(vo -> targetNames.contains(vo.getDisplayName()))
                    .collect(Collectors.toMap(
                            EnumerationItemTreeVO::getDisplayName,
                            vo -> vo,
                            (existing, replacement) -> existing
                    ));

            OutRuleItemVO outRuleItemVO = new OutRuleItemVO();
            OutRuleItemVO outRuleItemVO1 = new OutRuleItemVO();
            OutRuleItemVO outRuleItemVO2 = new OutRuleItemVO();

            EnumerationItemTreeVO isRequired = attrMap.get("是否必须");
            EnumerationItemTreeVO immediateSubmit = attrMap.get("立即提交");
            EnumerationItemTreeVO anySubmit = attrMap.get("任一提交");

            outRuleItemVO.setAttributeOid(isRequired.getId());
            outRuleItemVO.setAttributeOtype(isRequired.getOtype());
            if (isRequired.getHasChildren()) {
                List<EnumerationItemTreeVO> attributeValueList = isRequired.getChildren();
                EnumerationItemTreeVO attributeValueItem = attributeValueList.stream()
                        .filter(item -> item.getDisplayName().equals(materialDTO.getIsRequired()))
                        .findFirst()
                        .orElse(null);
                outRuleItemVO.setAttributeValueOid(attributeValueItem.getId());
                outRuleItemVO.setAttributeValueOtype(attributeValueItem.getOtype());
                outRuleVO.getOutRuleItemList().add(outRuleItemVO);
            }

            outRuleItemVO1.setAttributeOid(immediateSubmit.getId());
            outRuleItemVO1.setAttributeOtype(immediateSubmit.getOtype());
            if (immediateSubmit.getHasChildren()) {
                List<EnumerationItemTreeVO> attributeValueList = immediateSubmit.getChildren();
                EnumerationItemTreeVO attributeValueItem = attributeValueList.stream()
                        .filter(item -> item.getDisplayName().equals(materialDTO.getImmediateSubmit()))
                        .findFirst()
                        .orElse(null);
                outRuleItemVO1.setAttributeValueOid(attributeValueItem.getId());
                outRuleItemVO1.setAttributeValueOtype(attributeValueItem.getOtype());
                outRuleVO.getOutRuleItemList().add(outRuleItemVO1);
            }

            outRuleItemVO2.setAttributeOid(isRequired.getId());
            outRuleItemVO2.setAttributeOtype(isRequired.getOtype());
            if (isRequired.getHasChildren()) {
                List<EnumerationItemTreeVO> attributeValueList = anySubmit.getChildren();
                EnumerationItemTreeVO attributeValueItem = attributeValueList.stream()
                        .filter(item -> item.getDisplayName().equals(materialDTO.getAnySubmit()))
                        .findFirst()
                        .orElse(null);
                outRuleItemVO2.setAttributeValueOid(attributeValueItem.getId());
                outRuleItemVO2.setAttributeValueOtype(attributeValueItem.getOtype());
                outRuleVO.getOutRuleItemList().add(outRuleItemVO2);
            }
            this.typpmOutRuleService.insertOutRule(outRuleVO);

            //通过类型关联参考对象
            SearchTypeDTO searchTypeDTO = rtTaskMapper.selectTypeByName(materialDTO.getBomMaterialType());
            SearchConditionDTO conditionDTO = new SearchConditionDTO();
            conditionDTO.setConditionJoint("and");
            conditionDTO.setKeyword(materialDTO.getBomMaterialNumber());
            conditionDTO.setNeedCount(false);
            conditionDTO.setPageNum(1);
            conditionDTO.setPageSize(20);
            conditionDTO.setTypeList(Collections.singletonList(searchTypeDTO));

            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
            headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
            HttpEntity<SearchConditionDTO> requestEntity = new HttpEntity<>(conditionDTO, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    queryConditionUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String jsonBody = responseEntity.getBody();
                ObjectMapper objectMapper = new CustomObjectMapper(); // 应用日期解析规则
                try {
                    ResponseResult<PageInfo<ResultEntityVO>> responseResult = objectMapper.readValue(
                            jsonBody,
                            new TypeReference<ResponseResult<PageInfo<ResultEntityVO>>>() {}
                    );
                    if (ObjectUtil.isNotNull(responseResult)) {
                        // 返回分页数据
                        List<ResultEntityVO> remoteObjList = responseResult.getData().getList();
                        List<ResultEntityVO> filteredList = remoteObjList.stream()
                                .filter(vo -> Objects.equals(vo.getObjectNumber(), materialDTO.getBomMaterialNumber()))
                                .collect(Collectors.toList());
                        if (CollUtil.isEmpty(filteredList) || filteredList.size() != 1) {
                            throw RTErrorCodeEnum.TYPEOBJ_NOT_EXIST.getException("该类型对象不存在或编码重复");
                        }
                        BatchInsertDocVO batchInsetDocVO = new BatchInsertDocVO();
                        batchInsetDocVO.setDocOtype("add");
                        batchInsetDocVO.setLocalRepositoryUid("javaPDM");
                        batchInsetDocVO.setParentNodeOid(taskDTO.getOid());
                        batchInsetDocVO.setParentNodeOtype(TableTypeConstrant.TY_JOB_OTYPE);
                        batchInsetDocVO.setProjectOid(dto.getProjectID());
                        batchInsetDocVO.setType("IN");
                        List<DocDetailsVO> docDetailsVOS = BeanUtil.copyToList(filteredList, DocDetailsVO.class);
                        batchInsetDocVO.setDocList(docDetailsVOS);
                        this.typpmRemotePdmService.insertRemoteDoc(batchInsetDocVO);
                    } else {
                        assert responseResult != null;
                        throw new RuntimeException("接口返回异常：" + responseResult.getMessage());
                    }

                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }

        }


        for (IssueDTO issueDTO : issueDTOList) {
            RTImportTaskDTO taskDTO = new RTImportTaskDTO();
            taskDTO.setName(issueDTO.getIssueNumber() + "—" + issueDTO.getTaskName());
            taskDTO.setState("未读");
            taskDTO.setStateDisplayName("未读");
            taskDTO.setParentOTYPE(TableTypeConstrant.TY_JOB_OTYPE);
            taskDTO.setParentOID(dto.getJobId());
            taskDTO.setJobId(dto.getJobId());

            taskDTO.setProjectID(dto.getProjectID());
            taskDTO.setProjectName(dto.getProjectName());
            taskDTO.setPlanoid(dto.getPlanoid());

            taskDTO.setCreatorName(TyAccountContext.getUser().getName());
            taskDTO.setCreatorOID(TyAccountContext.getUser().getOid().toString());
            taskDTO.setCreatorDescription(TyAccountContext.getUser().getDescription());
            taskDTO.setCreatorOTYPE((TyAccountContext.getUser().getOtype()));
            UserDO userDO = typlmUserService.queryUserByName(issueDTO.getExecutor());

            taskDTO.setExecutorName(issueDTO.getExecutor());
            taskDTO.setExecutorOID(userDO.getOid().toString());
            taskDTO.setOwnerOTYPE(userDO.getOtype());
            taskDTO.setExecutorOTYPE(userDO.getOtype());
            taskDTO.setExecutorDescription(userDO.getDescription());

            Map<String, Object> params = new HashMap<>();
            params.put("containeroid", dto.getProjectID());
            params.put("usertype", "USER");
            PageInfo<TyppmUserEx> result = this.typpmPlanResourceService.queryPrjTeamUserByPrjOid(params, null, null);


            result.getList().stream()
                    .filter(typpmUserEx -> typpmUserEx.getOid().equals(String.valueOf(userDO.getOid())))
                    .findFirst()
                    .ifPresent(typpmUserEx -> {
                        taskDTO.setExecutorGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setOwnerGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setExecutorGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                        taskDTO.setOwnerGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                    });

            String plannedStartTime = issueDTO.getPlannedStartTime();
            String plannedFinishTime = issueDTO.getPlannedFinishTime();
            // 处理计划日期（跳过周末）
            LocalDateTime[] processedDates = DateUtils.processPlanDates(plannedStartTime, plannedFinishTime);
            taskDTO.setStartdate(processedDates[0]);
            taskDTO.setFinishdate(processedDates[1]);
            taskDTO.setSchedule(WorkdayCalculator.calculateWorkdayDuration(
                    processedDates[0],
                    processedDates[1]
            ));

            childList.add(taskDTO);


            //  子任务继承父任务的交付规则
            params.put("jobOid", dto.getJobId());
            params.put("markfordelete", 0L);
            PageInfo<OutRule> outRulePageInfo = outRuleService.queryOutRuleByPage(params);
            if (CollUtil.isNotEmpty(outRulePageInfo.getList())) {
                List<OutRuleVO> outRules = baseConvert.copyToList(outRulePageInfo.getList(), OutRuleVO.class);
                List<TyppmOutRuleItem> outRuleItems = this.getOutRuleItemList(
                        outRules.stream().map(OutRuleVO::getOid).collect(Collectors.toList()));
                for (OutRuleVO outRule : outRules) {
                    OutRuleParamVO outRuleVO = new OutRuleParamVO();
                    List<TyppmOutRuleItem> outRuleItemList = new ArrayList<>();
                    for (TyppmOutRuleItem outRuleItem : outRuleItems) {
                        if (!outRuleItem.getOutputRuleOid().equals(outRule.getOid()))
                            continue;
                        outRuleItem.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                        outRuleItemList.add(outRuleItem);
                    }
                    outRule.setJobOid(taskDTO.getOid());
                    outRule.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                    outRuleVO.setOutRule(outRule);
                    outRuleVO.setOutRuleItemList(baseConvert.copyToList(outRuleItemList, OutRuleItemVO.class));
                    this.typpmOutRuleService.insertOutRule(outRuleVO);
                }
            }
            //通过类型关联参考对象
            SearchConditionDTO conditionDTO = new SearchConditionDTO();
            SearchTypeDTO searchTypeDTO = new SearchTypeDTO();
            searchTypeDTO.setTypeOid(Tools.toBigInteger("221343775538937856"));
            searchTypeDTO.setTypeInthid(TableTypeConstrant.TY_CHANGEISSUE_OTYPE);

            conditionDTO.setConditionJoint("and");
            conditionDTO.setKeyword(issueDTO.getIssueNumber());
            conditionDTO.setNeedCount(false);
            conditionDTO.setPageNum(1);
            conditionDTO.setPageSize(20);
            conditionDTO.setTypeList(Collections.singletonList(searchTypeDTO));

            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
            headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
            HttpEntity<SearchConditionDTO> requestEntity = new HttpEntity<>(conditionDTO, headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    queryConditionUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String jsonBody = responseEntity.getBody();
                ObjectMapper objectMapper = new CustomObjectMapper(); // 应用日期解析规则
                try {
                    ResponseResult<PageInfo<ResultEntityVO>> responseResult = objectMapper.readValue(
                            jsonBody,
                            new TypeReference<ResponseResult<PageInfo<ResultEntityVO>>>() {}
                    );
                    if (ObjectUtil.isNotNull(responseResult)) {
                        // 返回分页数据
                        List<ResultEntityVO> remoteObjList = responseResult.getData().getList();
                        List<ResultEntityVO> filteredList = remoteObjList.stream()
                                .filter(vo -> Objects.equals(vo.getObjectNumber(), issueDTO.getIssueNumber()))
                                .collect(Collectors.toList());
                        if (CollUtil.isEmpty(filteredList) || filteredList.size() != 1) {
                            throw RTErrorCodeEnum.TYPEOBJ_NOT_EXIST.getException("该类型对象不存在或编码重复");
                        }
                        BatchInsertDocVO batchInsetDocVO = new BatchInsertDocVO();
                        batchInsetDocVO.setDocOtype("add");
                        batchInsetDocVO.setLocalRepositoryUid("javaPDM");
                        batchInsetDocVO.setParentNodeOid(taskDTO.getOid());
                        batchInsetDocVO.setParentNodeOtype(TableTypeConstrant.TY_JOB_OTYPE);
                        batchInsetDocVO.setProjectOid(dto.getProjectID());
                        batchInsetDocVO.setType("IN");
                        List<DocDetailsVO> docDetailsVOS = BeanUtil.copyToList(filteredList, DocDetailsVO.class);
                        batchInsetDocVO.setDocList(docDetailsVOS);
                        this.typpmRemotePdmService.insertRemoteDoc(batchInsetDocVO);
                    } else {
                        assert responseResult != null;
                        throw new RuntimeException("接口返回异常：" + responseResult.getMessage());
                    }

                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        for (RiskDTO riskDTO : riskDTOList) {
            RTImportTaskDTO taskDTO = new RTImportTaskDTO();
            taskDTO.setName(riskDTO.getRiskNumber() + "—" + riskDTO.getTaskName());
            taskDTO.setState("未读");
            taskDTO.setStateDisplayName("未读");
            taskDTO.setParentOTYPE(TableTypeConstrant.TY_JOB_OTYPE);
            taskDTO.setParentOID(dto.getJobId());
            taskDTO.setJobId(dto.getJobId());

            taskDTO.setProjectID(dto.getProjectID());
            taskDTO.setProjectName(dto.getProjectName());
            taskDTO.setPlanoid(dto.getPlanoid());

            taskDTO.setCreatorName(TyAccountContext.getUser().getName());
            taskDTO.setCreatorOID(TyAccountContext.getUser().getOid().toString());
            taskDTO.setCreatorDescription(TyAccountContext.getUser().getDescription());
            taskDTO.setCreatorOTYPE((TyAccountContext.getUser().getOtype()));
            UserDO userDO = typlmUserService.queryUserByName(riskDTO.getExecutor());

            taskDTO.setExecutorName(riskDTO.getExecutor());
            taskDTO.setExecutorOID(userDO.getOid().toString());
            taskDTO.setOwnerOTYPE(userDO.getOtype());
            taskDTO.setExecutorOTYPE(userDO.getOtype());
            taskDTO.setExecutorDescription(userDO.getDescription());

            Map<String, Object> params = new HashMap<>();
            params.put("containeroid", dto.getProjectID());
            params.put("usertype", "USER");
            PageInfo<TyppmUserEx> result = this.typpmPlanResourceService.queryPrjTeamUserByPrjOid(params, null, null);


            result.getList().stream()
                    .filter(typpmUserEx -> typpmUserEx.getOid().equals(String.valueOf(userDO.getOid())))
                    .findFirst()
                    .ifPresent(typpmUserEx -> {
                        taskDTO.setExecutorGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setOwnerGroupOid(typpmUserEx.getGroupOid());
                        taskDTO.setExecutorGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                        taskDTO.setOwnerGroupOtype(TableTypeConstrant.TY_GROUP_OTYPE);
                    });

            String plannedStartTime = riskDTO.getPlannedStartTime();
            String plannedFinishTime = riskDTO.getPlannedFinishTime();
            // 处理计划日期（跳过周末）
            LocalDateTime[] processedDates = DateUtils.processPlanDates(plannedStartTime, plannedFinishTime);
            taskDTO.setStartdate(processedDates[0]);
            taskDTO.setFinishdate(processedDates[1]);
            taskDTO.setSchedule(WorkdayCalculator.calculateWorkdayDuration(
                    processedDates[0],
                    processedDates[1]
            ));

            childList.add(taskDTO);


            //  子任务继承父任务的交付规则
            params.put("jobOid", dto.getJobId());
            params.put("markfordelete", 0L);
            PageInfo<OutRule> outRulePageInfo = outRuleService.queryOutRuleByPage(params);
            if (CollUtil.isNotEmpty(outRulePageInfo.getList())) {
                List<OutRuleVO> outRules = baseConvert.copyToList(outRulePageInfo.getList(), OutRuleVO.class);
                List<TyppmOutRuleItem> outRuleItems = this.getOutRuleItemList(
                        outRules.stream().map(OutRuleVO::getOid).collect(Collectors.toList()));
                for (OutRuleVO outRule : outRules) {
                    OutRuleParamVO outRuleVO = new OutRuleParamVO();
                    List<TyppmOutRuleItem> outRuleItemList = new ArrayList<>();
                    for (TyppmOutRuleItem outRuleItem : outRuleItems) {
                        if (!outRuleItem.getOutputRuleOid().equals(outRule.getOid()))
                            continue;
                        outRuleItem.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                        outRuleItemList.add(outRuleItem);
                    }
                    outRule.setJobOid(taskDTO.getOid());
                    outRule.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                    outRuleVO.setOutRule(outRule);
                    outRuleVO.setOutRuleItemList(baseConvert.copyToList(outRuleItemList, OutRuleItemVO.class));
                    this.typpmOutRuleService.insertOutRule(outRuleVO);
                }
            }
            //通过类型关联参考对象
            SearchConditionDTO conditionDTO = new SearchConditionDTO();
//            SearchTypeDTO searchTypeDTO = new SearchTypeDTO();
//            searchTypeDTO.setTypeOid(Tools.toBigInteger("221343775538937856"));
//            searchTypeDTO.setTypeInthid(TableTypeConstrant.TY_CHANGEISSUE_OTYPE);

            conditionDTO.setConditionJoint("and");
            conditionDTO.setKeyword(riskDTO.getRiskNumber());
            conditionDTO.setNeedCount(false);
            conditionDTO.setPageNum(1);
            conditionDTO.setPageSize(20);
            conditionDTO.setNeedThumbnailFile(true);
            //conditionDTO.setTypeList(Collections.singletonList(searchTypeDTO));

            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.AUTHORIZATION, TyAccountContext.getToken());
            headers.set(HttpHeaders.CONTENT_TYPE, "application/json");
            HttpEntity<SearchConditionDTO> requestEntity = new HttpEntity<>(conditionDTO, headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    queryConditionUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            if (responseEntity.getStatusCode().is2xxSuccessful()) {
                String jsonBody = responseEntity.getBody();
                ObjectMapper objectMapper = new CustomObjectMapper(); // 应用日期解析规则
                try {
                    ResponseResult<PageInfo<ResultEntityVO>> responseResult = objectMapper.readValue(
                            jsonBody,
                            new TypeReference<ResponseResult<PageInfo<ResultEntityVO>>>() {}
                    );
                    if (ObjectUtil.isNotNull(responseResult)) {
                        // 返回分页数据
                        List<ResultEntityVO> remoteObjList = responseResult.getData().getList();
                        List<ResultEntityVO> filteredList = remoteObjList.stream()
                                .filter(vo -> Objects.equals(vo.getObjectNumber(), riskDTO.getRiskNumber()))
                                .collect(Collectors.toList());
                        if (CollUtil.isEmpty(filteredList) || filteredList.size() != 1) {
                            throw RTErrorCodeEnum.TYPEOBJ_NOT_EXIST.getException("该类型对象不存在或编码重复");
                        }
                        BatchInsertDocVO batchInsetDocVO = new BatchInsertDocVO();
                        batchInsetDocVO.setDocOtype("add");
                        batchInsetDocVO.setLocalRepositoryUid("javaPDM");
                        batchInsetDocVO.setParentNodeOid(taskDTO.getOid());
                        batchInsetDocVO.setParentNodeOtype(TableTypeConstrant.TY_JOB_OTYPE);
                        batchInsetDocVO.setProjectOid(dto.getProjectID());
                        batchInsetDocVO.setType("IN");
                        List<DocDetailsVO> docDetailsVOS = BeanUtil.copyToList(filteredList, DocDetailsVO.class);
                        batchInsetDocVO.setDocList(docDetailsVOS);
                        this.typpmRemotePdmService.insertRemoteDoc(batchInsetDocVO);
                    } else {
                        assert responseResult != null;
                        throw new RuntimeException("接口返回异常：" + responseResult.getMessage());
                    }

                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        batchJobDTO.setChildList(childList);
        this.typpmJobService.checkJobName(batchJobDTO);
        this.typpmJobService.batchCheckCreateJobDTO(batchJobDTO);
        List<TyppmJobDTO> result = this.typpmJobService.batchCreateJobListByParentJob(batchJobDTO);
        return result;

    }

    @Override
    public RTTaskVO checkTaskOutRule(String jobId) {
        //1.判断当前关联是否完成
        if (existSalveJob(jobId)) {
            throw RTErrorCodeEnum.RELATIONJOB_NOT_COMPLETE.getException("关联项目任务的子任务未完成,无法提交");
        }

        //2.判断当前任务是否是临时任务
        RTPrjTaskJobLinkDO taskJobLinkDO = rtTaskMapper.existTemporaryTask(jobId);
        if (ObjectUtil.isNotNull(taskJobLinkDO)) {
            return new RTTaskVO(0, null);
        }

        // 3.获取当前任务的交付物规则列表
        PageInfo<TyppmOutRuleDTO> result = this.typpmOutRuleService.queryOutRuleByPage(
                jobId, null, null, null);
        List<TyppmOutRuleDTO> ruleList = result.getList();
        if (CollectionUtil.isEmpty(ruleList)) {
            String newConditionApproval = determineConditionApproval(ruleList);
            updateJobConditionApproval(Tools.toBigInteger(jobId), newConditionApproval);
            return new RTTaskVO(0, ruleList);
        }
        List<TyppmOutRuleDTO> delayOutRules = processRuleAttributes(ruleList);
        //4.更新任务属性
        String newConditionApproval = determineConditionApproval(delayOutRules);
        updateJobConditionApproval(Tools.toBigInteger(jobId), newConditionApproval);
        int sum=rtTaskMapper.queryTempoaryCount(jobId);
        return new RTTaskVO(delayOutRules.size()-sum, delayOutRules);
    }

    @Override
    @Transactional
    public void addTemporaryJob(TyppmJobDTO job, List<TyppmCheckItem> typpmCheckItemList,
                                List<DeliverRemoteDTO> deliverRemoteList, boolean valid) {
        //1.新增临时任务
        job.setOid(snowflakeIdComponent.getInstance().nextId().toString());
        typpmJobService.insertJob(job, job.getCheckItemList(), job.getDeliverRemoteList(), true);
        //2.构建iba属性与原任务关联
        bindAndSaveSingleIbaAttribute(Tools.toBigInteger(job.getOid()), TableTypeConstrant.TY_JOB_OTYPE,
                                      "TaskInformation", job.getOriTaskName());

        Map<String, Object> params = new HashMap<>();
        params.put("jobOid", job.getOriTaskOID());
        params.put("markfordelete", 0L);
        PageInfo<OutRule> outRulePageInfo = outRuleService.queryOutRuleByPage(params);
        List<OutRuleVO> outRules = baseConvert.copyToList(outRulePageInfo.getList(), OutRuleVO.class);
        List<OutRuleVO> filteredRules = outRules.stream()
                // 处理可能的null情况（集合元素、元素的oid、目标oid）
                .filter(rule -> rule != null
                        && rule.getOid() != null
                        && job.getRtTaskVO()!=null
                        && job.getRtTaskVO().getOutRule()!=null
                        && job.getRtTaskVO().getOutRule().getOid() != null
                        && rule.getOid().equals(job.getRtTaskVO().getOutRule().getOid()))
                .collect(Collectors.toList());
        List<TyppmOutRuleItem> outRuleItems = this.getOutRuleItemList(
                filteredRules.stream().map(OutRuleVO::getOid).collect(Collectors.toList()));
        for (OutRuleVO outRule : filteredRules) {
            OutRuleParamVO outRuleVO = new OutRuleParamVO();
            List<TyppmOutRuleItem> outRuleItemList = new ArrayList<>();
            for (TyppmOutRuleItem outRuleItem : outRuleItems) {
                if (!outRuleItem.getOutputRuleOid().equals(outRule.getOid()))
                    continue;
                outRuleItem.setOid(snowflakeIdComponent.getInstance().nextId().toString());
                outRuleItemList.add(outRuleItem);
            }
            outRule.setJobOid(job.getOid());
            outRule.setOid(snowflakeIdComponent.getInstance().nextId().toString());
            outRuleVO.setOutRule(outRule);
            outRuleVO.setOutRuleItemList(baseConvert.copyToList(outRuleItemList, OutRuleItemVO.class));
            this.typpmOutRuleService.insertOutRule(outRuleVO);
        }

        //第一次提交
        RTPrjTaskJobLinkDO rtPrjTaskJobLinkDO = new RTPrjTaskJobLinkDO();
        rtPrjTaskJobLinkDO.setTaskoid(Tools.toBigInteger(job.getOid()));
        rtPrjTaskJobLinkDO.setJoboid(Tools.toBigInteger(job.getOriTaskOID()));
        rtPrjTaskJobLinkDO.setOid(snowflakeIdComponent.getInstance().nextId());
        rtPrjTaskJobLinkDO.setStatus("0");//临时任务未提交
        TyplmEntityBaseUtil.fillCommonFieldForCreate(rtPrjTaskJobLinkDO);
        rtTaskMapper.insertTaskLink(rtPrjTaskJobLinkDO);

//        String status = rtTaskMapper.selectOriTask(job.getOriTaskOID());
//        if (StringUtils.equals(status, "已提交")) {
//            return;
//        }
//
//        //3.提交原任务
//        RequestBase<JobStatusUpdateDTO> requestBase = new RequestBase<>();
//        JobStatusUpdateDTO jobStatusUpdateDTO = new JobStatusUpdateDTO();
//        jobStatusUpdateDTO.setJobId(job.getOriTaskOID());
//        TyppmOperationRecordVO operationRecordVO = new TyppmOperationRecordVO();
//        operationRecordVO.setPassname("提交");
//        operationRecordVO.setRemark("1");
//        jobStatusUpdateDTO.setOperationRecordVO(operationRecordVO);
//        requestBase.setInput(jobStatusUpdateDTO);
//        typpmJobService.setSubmitState(requestBase.getInput(), "已提交");

    }

    @Override
    @Transactional
    public List<RTCheckTableVO> checkCompleteOutRule(BigInteger projectOid) {
        String projectType = rtTaskMapper.selectProjectTypeNameByOid(String.valueOf(projectOid));
        List<String> inspectionCheckTableIdList= rtTaskMapper.selectInspectionChecklistDoc();
        if (CollUtil.isEmpty(inspectionCheckTableIdList)){
            throw RTErrorCodeEnum.DOC_NOT_EXIST.getException("齐套性点检表不存在");
        }else if (inspectionCheckTableIdList.size()!=1){
            throw RTErrorCodeEnum.DOC_EXIST_MULTIPLE.getException("系统存在多个齐套性点检表");
        }
        IdentifierEntity entity = new IdentifierEntity();
        entity.setOid(Tools.toBigInteger(inspectionCheckTableIdList.get(0)));
        entity.setOtype(TableTypeConstrant.TY_DOC_OTYPE);
        List<FileDataVO> fileListByEntity = this.fileHandleService.getFileListByEntity(entity);
        if (CollUtil.isEmpty(fileListByEntity)) {
            throw RTErrorCodeEnum.DOC_NOT_EXIST.getException("齐套性点检表不存在");
        }
        String fileID = fileListByEntity.get(0).getFileID();
        if (StringUtils.isBlank(fileID)){
            throw RTErrorCodeEnum.DOC_NOT_EXIST.getException("齐套性点检表不存在");
        }
        return dealOutRule(Tools.toBigInteger(fileID), projectType, projectOid);
    }

    @Override
    @Transactional
    public boolean checkSubmitOutRule(String jobOid) {
        PageInfo<TyppmOutRuleDTO> result = typpmOutRuleService.queryOutRuleByPage(jobOid, null, null, null);
        List<TyppmOutRuleDTO> outRulelist = result.getList();

        for (TyppmOutRuleDTO typpmOutRuleDTO : outRulelist) {
            Map<String, String> map = parseRuleAttributes(typpmOutRuleDTO.getRuleDisplayName());
            String value = map.get(RTPlmConstant.REQUIRED);
            if(StringUtils.equals(value,RTPlmConstant.NO) && CollUtil.isEmpty(typpmOutRuleDTO.getDeliverName())){
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional
    public void insertOutRole(JSONObject jsonObject) {
        String roleId = jsonObject.getString("roletypeOid");
        String jobId = jsonObject.getString("jobId");
        String parentId = jsonObject.getString("parentId");
        if (StrUtil.isBlank(roleId)){
            throw new RuntimeException("roleId不能为空");
        }
        if (StrUtil.isBlank(jobId)){
            throw new RuntimeException("jobId不能为空");
        }
        if (StrUtil.isBlank(parentId)){
            throw new RuntimeException("parentId不能为空");
        }

        PageInfo<TyppmOutRuleDTO> result = this.typpmOutRuleService.queryOutRuleByPage(parentId, "", 1, 999);
        List<TyppmOutRuleDTO> list = result.getList();

        Optional<TyppmOutRuleDTO> any = list.stream().filter(f -> f.getOid().equals(roleId)).findAny();
        if (any.isPresent()){
            TyppmOutRuleDTO typpmOutRuleDTO = any.get();
            OutRuleParamVO outRuleParamVO = new OutRuleParamVO();
            OutRuleVO outRuleVO = buildOutRuleVO(typpmOutRuleDTO, jobId);
            outRuleParamVO.setOutRule(outRuleVO);
            List<OutRuleItemVO> outRuleItemList = new ArrayList<>();
            outRuleParamVO.setOutRuleItemList(outRuleItemList);
            buildOutRuleItemVOList(typpmOutRuleDTO, outRuleItemList);
            typpmOutRuleService.insertOutRule(outRuleParamVO);
        }
    }

    @Override
    @Transactional
    public boolean updateJobStatus(String oid, String riskType) {
        if (!com.alibaba.cloud.commons.lang.StringUtils.isEmpty(
                oid) && !com.alibaba.cloud.commons.lang.StringUtils.isEmpty(riskType)) {

            List<TyppmJobDTO> jobByOid = typpmJobService.getJobByOid(oid);


            if (!CollUtil.isEmpty(jobByOid)) {
                TyppmJobDTO typpmJobDTO = jobByOid.get(0);
                typpmJobDTO.setRiskType(riskType);
                JobRemoteDTO jobRemoteDTO = new JobRemoteDTO();
                BeanUtils.copyProperties(typpmJobDTO, jobRemoteDTO);
                jobRemoteDTO.setCreatoroid(new BigInteger(typpmJobDTO.getCreatorOID()));
                jobRemoteDTO.setExecutorOID(new BigInteger(typpmJobDTO.getExecutorOID()));
                jobRemoteDTO.setUpdatoroid(new BigInteger(typpmJobDTO.getUpdatorOID()));
                jobRemoteDTO.setCreatorotype(typpmJobDTO.getCreatorOTYPE());
                jobRemoteDTO.setExecutorOTYPE(typpmJobDTO.getExecutorOTYPE());
                jobRemoteDTO.setUpdatorotype(typpmJobDTO.getUpdatorOTYPE());
                jobRemoteDTO.setPlanoid(new BigInteger(typpmJobDTO.getPlanoid()));
                jobRemoteDTO.setParentOID(new BigInteger(typpmJobDTO.getParentOID()));
                jobRemoteDTO.setOwnerGroupOid(new BigInteger(typpmJobDTO.getOwnerGroupOid()));
                jobRemoteDTO.setOwnerGroupOtype(typpmJobDTO.getOwnerGroupOtype());
                jobRemoteDTO.setExecutorGroupOid(new BigInteger(typpmJobDTO.getExecutorGroupOid()));
                jobRemoteDTO.setExecutorGroupOtype(typpmJobDTO.getExecutorGroupOtype());
                jobRemoteDTO.setPlanoid(new BigInteger(typpmJobDTO.getPlanoid()));
                jobRemoteDTO.setProjectID(new BigInteger(typpmJobDTO.getProjectID()));
                jobRemoteDTO.setOid(new BigInteger(typpmJobDTO.getOid()));
                jobRemoteDTO.setOtype(typpmJobDTO.getOtype());
                jobRemoteDTO.setTypeoid(new BigInteger(typpmJobDTO.getTypeOID()));
                jobRemoteDTO.setTypeotype(typpmJobDTO.getTypeOTYPE());
                jobRemoteDTO.setActivityID(new BigInteger(typpmJobDTO.getActivityID()));
                typpmJobService.updateJobAndCalculate(jobRemoteDTO);
            }
            return true;
        }
        return false;
    }

    private void buildOutRuleItemVOList(TyppmOutRuleDTO parentOutRule, List<OutRuleItemVO> outRuleItemList) {
        String ruleDisplayName = parentOutRule.getRuleDisplayName();
        List<EnumerationItemTreeVO> enumerationItemTreeList = this.typpmOutRuleService.queryRuleAttributes(
                parentOutRule.getRuletypeOid());
        Map<String, EnumerationItemTreeVO> enumerationItemTreeMap = enumerationItemTreeList.stream()
                .collect(Collectors.toMap(
                        EnumerationItemTreeVO::getDisplayName,
                        Function.identity(),
                        (v1, v2) -> v1
                ));

        if(StringUtils.isNotEmpty(ruleDisplayName) && StringUtils.isNotBlank(ruleDisplayName)){
            for (String attrAndValue : ruleDisplayName.split(";")) {
                String[] rule = attrAndValue.split(":");
                String key = rule[0];
                String value = rule[1];
                if(enumerationItemTreeMap.containsKey(key)){
                    OutRuleItemVO outRuleItemVO = new OutRuleItemVO();
                    EnumerationItemTreeVO enumerationItemTreeVO = enumerationItemTreeMap.get(key);
                    outRuleItemVO.setAttributeOid(enumerationItemTreeVO.getId());
                    outRuleItemVO.setAttributeOtype(enumerationItemTreeVO.getOtype());
                    for (EnumerationItemTreeVO child : enumerationItemTreeVO.getChildren()) {
                        if(child.getDisplayName().equals(value)){
                            outRuleItemVO.setAttributeValueOid(child.getId());
                            outRuleItemVO.setAttributeValueOtype(child.getOtype());
                            outRuleItemList.add(outRuleItemVO);
                        }
                    }
                }
            }
        }
    }
    private OutRuleVO buildOutRuleVO(TyppmOutRuleDTO parentOutRule, String currentJobId) {
        OutRuleVO outRule = new OutRuleVO();
        String ruleTypeOid = parentOutRule.getRuletypeOid();
        String ruleTypeOtype = parentOutRule.getRuletypeOtype();
        String name = parentOutRule.getName();
        Long checkDelivers = parentOutRule.getCheckDelivers();

        outRule.setRuletypeOid(ruleTypeOid);
        outRule.setRuletypeOtype(ruleTypeOtype);
        outRule.setName(name);
        outRule.setCheckDelivers(checkDelivers);
        outRule.setJobOid(currentJobId);
        return outRule;
    }

    private List<RTCheckTableVO> dealOutRule(BigInteger fileId, String projectType, BigInteger projectOid) {
        log.info("==========提示信息==========> 开始进行检查");
        List<BigInteger> fileIds = new ArrayList<>();
        fileIds.add(fileId);
        fileIds.addAll(this.typlmContentReferenceLinkService.queryFileIlluStrationFileOids(fileIds));
        List<CadDownloadFileVO> cadDownloadFileVOList = this.typlmFileTransferService.getDownloadFileDTOS(fileIds, TyAccountContext.getUser().getOid());
        List<DownloadFileDTO> downloadFileDTOList = TyplmDownloadToolUtil.getDownloadFileDTOS(cadDownloadFileVOList);
        DownloadFileDTO downloadFileDTO = downloadFileDTOList.get(0);
        this.typlmEncryptService.recordFileNameKeys(new BigInteger(downloadFileDTO.getFileId()));
        DownLoadFileVO downLoadFileVO = this.typlmContentDataService.getInputStream(downloadFileDTO);
        File file = downLoadFileVO.getFile();
        String fileName = downLoadFileVO.getFileName();
        try {
            MultipartFile multipartFile = new MockMultipartFile(fileName, fileName, "application/octet-stream",FileUtils.openInputStream(file));

            Map<String, String> checkMap = ExcelToList.getExcelPropertySettingMapByClass(CheckTableDTO.class);
            Workbook workbook = getWorkbook(multipartFile);


            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                String sheetName = sheet.getSheetName();
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        cell.setCellType(CellType.STRING);
                    }
                }
                // 2. 判断工作表是否需要处理（精确匹配或按_分割后的类型匹配）
                boolean remark = false;
                // 精确匹配：工作表名与prjType完全相同
                if (sheetName.equals(projectType)) {
                    remark = true;
                } else if (sheetName.contains("_")) {
                    // 按_分割符匹配：如果工作表名包含_，判断其中是否有与prjType匹配的部分
                    String[] sheetTypeParts = sheetName.split("_");
                    for (String part : sheetTypeParts) {
                        if (part.equals(projectType)) {
                            remark = true;
                            break;
                        }
                    }
                }

                if (remark) {
                    List<RTCheckTableVO> rtCheckTableVOList = new LinkedList<>();
                    List<CheckTableDTO> checkTableDTOList = ExcelToList.excelToList(i, 0, workbook, CheckTableDTO.class,
                                                                                    checkMap);

                    Map<String, List<CheckTableDTO>> stageMap = checkTableDTOList.parallelStream().collect(
                            Collectors.groupingBy(CheckTableDTO::getStage));

                    if (CollUtil.isEmpty(stageMap)) {
                        return null;
                    }
                    JobTreeQueryDTO queryDTO = new JobTreeQueryDTO();
                    queryDTO.setProjectOid(String.valueOf(projectOid));
                    // 一级阶段任务无交付物规则
                    List<TyppmJobVO> jobVOS = this.typpmJobService.getJobTreeByParams(queryDTO);
                    Map<String, TyppmJobVO> jobVOMap = jobVOS.stream().collect(
                            Collectors.toMap(TyppmJobVO::getName, item -> item, (old, newItem) -> newItem));
                    for (Map.Entry<String, List<CheckTableDTO>> entry : stageMap.entrySet()) {
                        String key = entry.getKey();
                        Map<String, CheckTableDTO> outRuleMap = entry.getValue().stream().collect(
                                Collectors.toMap(CheckTableDTO::getOutput, item -> item, (old, newItem) -> newItem));
                        if(jobVOMap.containsKey(key)){
                            TyppmJobVO jobVO = jobVOMap.get(key);
                            dealJobOutRules(jobVO, outRuleMap);
                        }
                        ArrayList<CheckTableDTO> list = ListUtil.toList(outRuleMap.values());
                        List<RTCheckTableVO> rtCheckTableVOS = BeanUtil.copyToList(list, RTCheckTableVO.class);
                        rtCheckTableVOList.addAll(rtCheckTableVOS);
                    }
                    return rtCheckTableVOList.stream().sorted(
                                    Comparator.comparing(RTCheckTableVO::getNumber,
                                                         Comparator.nullsFirst(Comparator.naturalOrder())))
                            .collect(Collectors.toList());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }


//    private void handleOutRule(List<RTCheckTableVO> rtCheckTableVOList, List<CheckTableDTO> checkTableDTOList,
//                               BigInteger oid) {
//
//        Map<String, List<CheckTableDTO>> stageMap = checkTableDTOList.parallelStream().collect(
//                Collectors.groupingBy(CheckTableDTO::getStage));
//
//        if (CollUtil.isEmpty(stageMap)) {
//            return;
//        }
//        JobTreeQueryDTO queryDTO = new JobTreeQueryDTO();
//        queryDTO.setProjectOid(String.valueOf(oid));
//        // 一级阶段任务无交付物规则
//        List<TyppmJobVO> jobVOS = this.typpmJobService.getJobTreeByParams(queryDTO);
//        Map<String, TyppmJobVO> jobVOMap = jobVOS.stream().collect(
//                Collectors.toMap(TyppmJobVO::getOid, item -> item, (old, newItem) -> newItem));
//        for (Map.Entry<String, List<CheckTableDTO>> entry : stageMap.entrySet()) {
//            String key = entry.getKey();
//            Map<String, CheckTableDTO> outRuleMap = entry.getValue().stream().collect(
//                    Collectors.toMap(CheckTableDTO::getOutput, item -> item, (old, newItem) -> newItem));
//            if(jobVOMap.containsKey(key)){
//                TyppmJobVO jobVO = jobVOMap.get(key);
//                    dealJobOutRules(jobVO, outRuleMap);
//            }
//            ArrayList<CheckTableDTO> list = ListUtil.toList(outRuleMap.values());
//            List<RTCheckTableVO> rtCheckTableVOS = BeanUtil.copyToList(list, RTCheckTableVO.class);
//            rtCheckTableVOList.addAll(rtCheckTableVOS);
//        }

//        // 2. 查询项目下所有子任务（假设子任务通过项目OID查询，且包含扩展属性）
//
//        // 3. 按子任务的扩展属性（值=阶段名称）分组，得到“阶段名称→子任务列表”映射
//        // 4. 遍历每个阶段，处理关联的子任务及规则
//        stageMap.forEach((stageName, checkTableList) -> {
//            BigInteger b = rtTaskMapper.selectTaskIsExist(oid, stageName);
//            if (b.compareTo(new BigInteger("0"))==0){
//                return;
//            }
//
//            List<SubJobVO> subJobList = rtTaskMapper.selectSubJobsByPrjId(oid,stageName);
//            // 4.1 获取当前阶段对应的子任务列表（通过扩展属性关联）
//
//            if (CollUtil.isEmpty(subJobList)) {
//                return; // 无对应子任务则跳过当前阶段
//            }
//
//            // 4.2 遍历子任务，查询每个子任务的交付物规则
//            subJobList.forEach(subJob -> {
//                // 查询子任务的规则列表（假设子任务OID为subJob.getOid()）
//                List<TyppmOutRuleDTO> subJobRules = typpmOutRuleService
//                        .queryOutRuleByPage(subJob.getOid().toString(), null, null, null).getList();
//                if (CollUtil.isEmpty(subJobRules)) {
//                    return; // 无子任务规则则跳过
//                }
//                // 4.3 构建“规则类型名称→规则对象”映射（用于匹配CheckTable）
//                Map<String, List<TyppmOutRuleDTO>> ruleMap = subJobRules.stream()
//                        .collect(Collectors.groupingBy(
//                                TyppmOutRuleDTO::getRuletypeDisplayName, // 按规则类型名称分组
//                                Collectors.toList() // 同一类型的所有规则存入List
//                        ));
//                // 不再用matchedList中间集合，直接遍历CheckTable+规则列表，确保所有规则都处理
//                checkTableList.forEach(checkTable -> {
//                    String output = checkTable.getOutput();
//                    // 过滤output为空或无对应规则的情况
//                    if (output == null || !ruleMap.containsKey(output)) {
//                        return;
//                    }
//                    // 获取当前output对应的所有规则（含重复类型）
//                    List<TyppmOutRuleDTO> matchedRules = ruleMap.get(output);
//                    // 遍历每个规则，逐个生成VO（关键：重复规则都会生成对应的VO）
//                    matchedRules.forEach(subRule -> {
//                        RTCheckTableVO vo = new RTCheckTableVO();
//                        // 规则属性解析（原有逻辑不变）
//                        Map<String, String> ruleAttrs = parseRuleAttributes(subRule.getRuleDisplayName());
//                        vo.setIsRequired(ruleAttrs.get(RTPlmConstant.REQUIRED));
//                        vo.setImmediateSubmit(ruleAttrs.get(RTPlmConstant.SUBMIT));
//                        // 阶段与子任务信息（原有逻辑不变）
//                        vo.setStage(stageName);
//                        vo.setOutput(subRule.getRuletypeDisplayName());
//                        vo.setOutputOid(Tools.toBigInteger(subRule.getOid()));
//                        vo.setOutputType(subRule.getOtype());
//                        // CheckTable关联字段（原有逻辑不变）
//                        vo.setRepresentative(checkTable.getRepresentative());
//                        vo.setRemark(checkTable.getRemark());
//                        vo.setRequire(checkTable.getRequire());
//                        // 子任务交付物判断（原有逻辑不变）
//                        vo.setTag(CollUtil.isEmpty(subRule.getDeliverName()));
//                        vo.setN(checkTable.getNumber());
//                        // 归档状态（原有逻辑不变）
//                        vo.setStatus("是");
//                        List<RTPrjTaskJobLinkDO> prjTaskJobLinkDOS=rtTaskMapper.selectJobById(subJob.getOid());
//                        if (CollUtil.isNotEmpty(prjTaskJobLinkDOS)){
//                            for (RTPrjTaskJobLinkDO prjTaskJobLinkDO : prjTaskJobLinkDOS) {
//                                if (StringUtils.equals(prjTaskJobLinkDO.getStatus(),"0")){
//                                    vo.setStatus("否");
//                                    break;
//                                }
//                            }
//                        }else {
//                            vo.setStatus("否");
//                        }
//                        // 每个规则生成的VO都添加到结果列表（无丢失）
//                        rtCheckTableVOList.add(vo);
//                    });
//                });
//            });
//        });

//    }

    private void dealJobOutRules(TyppmJobVO jobVO, Map<String, CheckTableDTO> outRuleMap) {
        List<TyppmOutRuleDTO> subJobRules = typpmOutRuleService
                .queryOutRuleByPage(jobVO.getOid(), null, null, null).getList();
        if (CollUtil.isNotEmpty(subJobRules)) {
            Map<String, List<TyppmOutRuleDTO>> ruleMap = subJobRules.stream()
                    .collect(Collectors.groupingBy(
                            TyppmOutRuleDTO::getRuletypeDisplayName,
                            Collectors.toList()
                    ));
            for (Map.Entry<String, List<TyppmOutRuleDTO>> ruleEntity : ruleMap.entrySet()) {
                String key = ruleEntity.getKey();
                if(outRuleMap.containsKey(key)){
                    CheckTableDTO checkTableDTO = outRuleMap.get(key);
                    TyppmOutRuleDTO typpmOutRuleDTO = ruleEntity.getValue().get(0);
                    Map<String, String> ruleAttrs = parseRuleAttributes(typpmOutRuleDTO.getRuleDisplayName());
                    checkTableDTO.setIsRequired(ruleAttrs.get(RTPlmConstant.REQUIRED));
                    checkTableDTO.setImmediateSubmit(ruleAttrs.get(RTPlmConstant.SUBMIT));
                    if (CollUtil.isNotEmpty(typpmOutRuleDTO.getDeliverName())) {
                        checkTableDTO.setStatus("是");
                    } else {
                        checkTableDTO.setStatus("否");
                    }
                }
            }
        }
        List<TyppmJobVO> children = jobVO.getChildren();
        if (CollUtil.isNotEmpty(children)) {
            for (TyppmJobVO child : children) {
                dealJobOutRules(child, outRuleMap);
            }
        }
    }


    /**
     * 更新任务的条件通过属性
     */
    private void updateJobConditionApproval(BigInteger jobId, String newValue) {
        bindAndSaveSingleIbaAttribute(jobId, TableTypeConstrant.TY_JOB_OTYPE, ruleConditionKey, newValue);
    }


    private void bindAndSaveSingleIbaAttribute(BigInteger objOid, String objOtype, String attrKey, String attrValue) {
        // 1. 校验入参有效性
        if (objOid == null || StringUtils.isBlank(objOtype)
                || StringUtils.isBlank(attrKey) || StringUtils.isBlank(attrValue)) {
            log.warn("绑定IBA属性失败：参数不能为空，objOid={}, objOtype={}, attrKey={}",
                     objOid, objOtype, attrKey);
        }
        // 2. 创建IBA属性DTO
        IbaDTO ibaDTO = new IbaDTO();
        ibaDTO.setKey(attrKey);
        ibaDTO.setValue(attrValue);
        // 3. 创建"对象+属性"绑定DTO
        SaveObjIBADTO saveDTO = new SaveObjIBADTO();
        saveDTO.setObjIbaList(Collections.singletonList(ibaDTO));

        // 4. 设置对象基础信息
        saveDTO.setCTyEntityBaseDO(new CTyEntityBaseDO(objOid, objOtype));

        // 5. 批量保存（单对象）
        try {
            typlmAttributeValueService.batchSaveIBAByObjList(Collections.singletonList(saveDTO), false);
        } catch (Exception e) {
            log.error("绑定IBA属性失败，objOid={}, attrKey={}", objOid, attrKey, e);
        }
    }


    private String determineConditionApproval(List<TyppmOutRuleDTO> delayedRules) {
        // 如果存在"立即提交=否"的规则，设置为"条件通过"
        if (CollUtil.isNotEmpty(delayedRules)) {
            return "条件通过";
        }
        // 否则设置为"通过"
        return "通过";
    }

    private List<TyppmOutRuleDTO> processRuleAttributes(List<TyppmOutRuleDTO> ruleList) {
        List<TyppmOutRuleDTO> delayedRules = new ArrayList<>();
        for (TyppmOutRuleDTO rule : ruleList) {
            Map<String, String> ruleAttributes = parseRuleAttributes(rule.getRuleDisplayName());
            // 检查"任一提交"属性
            if (ruleAttributes.containsKey(RTPlmConstant.ANYSUBMISSION) &&
                    RTPlmConstant.OK.equals(ruleAttributes.get(RTPlmConstant.ANYSUBMISSION))) {
                List<BigInteger> typeOid = rtOutRuleMapper.selectAllTypeById(rule.getRuletypeOid());
                long count = ruleList.stream()
                        .filter(r -> typeOid.contains(new BigInteger(r.getRuletypeOid())))
                        .filter(r -> {
                            Map<String, String> attrs = parseRuleAttributes(r.getRuleDisplayName());
                            return attrs.containsKey(RTPlmConstant.ANYSUBMISSION) &&
                                    RTPlmConstant.OK.equals(attrs.get(RTPlmConstant.ANYSUBMISSION));
                        })
                        .count();
                if (count < 2) {
                    throw RTErrorCodeEnum.ANYSUBMISSION_UNIQUE_ERROR.getException("任一提交单独设置不生效");
                }
            }

            // 检查"是否必须"属性
            if (ruleAttributes.containsKey(RTPlmConstant.REQUIRED) &&
                    RTPlmConstant.OK.equals(ruleAttributes.get(RTPlmConstant.REQUIRED))) {
                if (CollectionUtil.isEmpty(rule.getDeliverName())) {
                    throw RTErrorCodeEnum.REMOTEOBJ_NOT_EXIST.getException(
                            "该规则下交付物不能为空，请添加交付物");
                }
            }
            // 处理"立即提交"属性
            if (ruleAttributes.containsKey(RTPlmConstant.SUBMIT) &&
                    RTPlmConstant.NO.equals(ruleAttributes.get(RTPlmConstant.SUBMIT))) {
                if(CollUtil.isEmpty(rule.getDeliverName())){
                    delayedRules.add(rule);
                }
            }
        }

        return delayedRules;
    }


    private Map<String, String> parseRuleAttributes(String ruleDisplayName) {
        Map<String, String> attributes = new HashMap<>();
        if (ruleDisplayName == null || ruleDisplayName.isEmpty()) {
            return attributes;
        }
        String[] pairs = ruleDisplayName.split(";");
        for (String pair : pairs) {
            int colonIndex = pair.indexOf(':');
            if (colonIndex > 0 && colonIndex < pair.length() - 1) {
                String key = pair.substring(0, colonIndex).trim();
                String value = pair.substring(colonIndex + 1).trim();
                attributes.put(key, value);
            }
        }
        return attributes;
    }


    private boolean existSalveJob(String jobId) {
        return rtProjectMapper.existSalveJob(jobId);
    }


    private List<TyppmOutRuleItem> getOutRuleItemList(List<String> oldRuleOidList) {
        OutRuleItemDTO params = new OutRuleItemDTO();
        params.setOldRuleOidList(oldRuleOidList.stream().map(BigInteger::new).collect(Collectors.toList()));
        params.setMarkForDelete(0L);
        List<OutRuleItem> outRuleItems = this.outRuleItemService.listOutRuleItemByRuleOidList(params);
        return this.baseConvert.copyToList(outRuleItems, TyppmOutRuleItem.class);
    }

    /**
     * 处理DTO列表中的日期字段
     */
    private void processDateFields(List<?> dtoList, Map<String, String> fieldMap) {
        // 定义需要处理的日期字段（根据实际情况调整）
        Set<String> dateFieldNames = new HashSet<>(Arrays.asList(
                "计划开始时间", "计划完成时间",
                "plannedStartTime", "plannedFinishTime"
        ));

        // 反转映射：Excel表头 -> 实体字段名
        Map<String, String> headerToFieldMap = new HashMap<>();
        for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
            headerToFieldMap.put(entry.getValue(), entry.getKey());
        }
        // 处理每个DTO对象
        for (Object dto : dtoList) {
            Class<?> dtoClass = dto.getClass();
            // 使用反射处理每个字段
            for (Field field : dtoClass.getDeclaredFields()) {
                // 检查是否为日期字段
                String fieldName = field.getName();
                if (dateFieldNames.contains(fieldName)) {
                    try {
                        field.setAccessible(true);
                        Object value = field.get(dto);

                        // 如果字段值是字符串类型，尝试转换为日期
                        if (value instanceof String) {
                            String dateStr = (String) value;

                            // 获取Excel表头（用于判断是否为结束时间）
                            String excelHeader = headerToFieldMap.getOrDefault(fieldName, fieldName);

                            // 转换为LocalDateTime
                            LocalDateTime dateTime = ExcelDateConverterUtil.convertToLocalDateTime(dateStr,
                                                                                                   excelHeader);

                            // 设置回DTO
                            if (dateTime != null) {
                                // 根据字段类型设置值
                                if (field.getType() == LocalDateTime.class) {
                                    field.set(dto, dateTime);
                                } else if (field.getType() == String.class) {
                                    // 格式化为字符串
                                    String formattedDate = dateTime.format(
                                            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    field.set(dto, formattedDate);
                                }
                                // 可根据需要添加其他类型的转换
                            }
                        }
                    } catch (Exception e) {
                        System.err.println("处理日期字段失败: " + fieldName + ", 错误: " + e.getMessage());
                    }
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createTemporaryJob(JobExtVO job) {
//        String projectID = job.getProjectID();
//        JobTreeQueryDTO queryDTO = new JobTreeQueryDTO();
//        queryDTO.setProjectOid(projectID);
//        List<TyppmJobVO> result = this.typpmJobService.getJobTreeByParams(queryDTO);
//        boolean flag = false;
//        for (TyppmJobVO typpmJobVO : result) {
//            if("临时任务".equals(typpmJobVO.getName())){
//                job.setParentOID(typpmJobVO.getOid());
//                job.setParentOTYPE(typpmJobVO.getOtype());
//                flag = true;
//            }
//        }
//        if(!flag){
//            // 创建临时任务
//            Map<String, Object> params = new HashMap<>();
//            params.put("getPlanDate", "1");
//            params.put("projectOID", projectID);
//            List<TyppmProjectDTO> list = this.typpmProjectService.queryProjectListByParams(params);
//            if (CollUtil.isEmpty(list)) {
//                throw SystemErrorCodeEnum.ENTITY_NONE.message("项目");
//            } else {
//                TyppmProjectDTO typpmProjectDTO = list.get(0);
//                LocalDateTime finishDate = typpmProjectDTO.getFinishDate();
//                LocalDateTime startDate = typpmProjectDTO.getStartDate();
//                String projectManager = typpmProjectDTO.getAdministratorsName();
//                String[] split = projectManager.split(",");
//                String username = "";
//                for (String user : split) {
//                    if(!user.contains("admin")&&!user.contains("user1")&&!user.contains("user2")){
//                        username = extractContentInParentheses(user);
//                    }
//                }
//
//                JobExtVO temporaryJob = new JobExtVO();
//                if(StringUtils.isNotEmpty(username)){
//                    UserDO userDO = typlmUserService.queryUserByName(username);
//                    temporaryJob.setExecutorOID(String.valueOf(userDO.getOid()));
//                    temporaryJob.setExecutorName(username);
//                    temporaryJob.setCreatorOID(String.valueOf(userDO.getOid()));
//                    temporaryJob.setCreatorName(username);
//
//                }
//                String oid = String.valueOf(snowflakeIdComponent.getInstance().nextId());
//                temporaryJob.setOid(oid);
//                temporaryJob.setName("临时任务");
//                temporaryJob.setOtype(TableTypeConstrant.TY_JOB_OTYPE);
//                temporaryJob.setSecurityLabels("非密");
//                temporaryJob.setProjectID(job.getProjectID());
//                temporaryJob.setParentOTYPE(job.getProjectID());
//                temporaryJob.setExecutorOTYPE(TableTypeConstrant.TY_USER_OTYPE);
//                temporaryJob.setCreatorOTYPE(TableTypeConstrant.TY_USER_OTYPE);
//                temporaryJob.setStartdate(startDate);
//                temporaryJob.setFinishdate(finishDate);
//                temporaryJob.setTypeOID(job.getTypeOID());
//                temporaryJob.setTypeOTYPE(job.getTypeOTYPE());
//                temporaryJob.setTag(0);
//                workItemService.createJob(job);
//
//                job.setParentOID(oid);
//                job.setParentOTYPE(TableTypeConstrant.TY_JOB_OTYPE);
//            }
//        }
        Map<String, List<String>> ibaAttribute = job.getIbaAttribute();
        String sourceJobOid = job.getJobID();
        ibaAttribute.put("ParentTaskId", Collections.singletonList(sourceJobOid));
        job.setIbaAttribute(ibaAttribute);
        job.setParentOID("");
        this.typpmJobService.checkCreateJobParams(job);
        TyppmJobDTO map = BeanMapper.map(job, TyppmJobDTO.class);
        this.typpmJobService.insertJob(map, map.getCheckItemList(), map.getDeliverRemoteList(), true);
        JobStatusUpdateDTO jobStatusUpdateDTO = this.typpmJobService.buildJobStatusUpdateDTO(map, "下达");
        this.typpmJobService.setJobState(jobStatusUpdateDTO, "未读");
        this.typpmJobService.calculate(map);
        this.typpmJobService.insertMeetingObjLink(job);
        workItemService.updatePlanStatus(sourceJobOid,"条件通过");

        //记录到临时任务表
        RtTemporaryTask rtTemporaryTask = new RtTemporaryTask();
        rtTemporaryTask.setOid(snowflakeIdComponent.getInstance().nextId());
        rtTemporaryTask.setPrjid(job.getProjectID());
        rtTemporaryTask.setPrjname(job.getProjectName());
        rtTemporaryTask.setJobid(job.getId());
        rtTemporaryTask.setJobname(job.getName());
        rtTemporaryTaskService.insert(rtTemporaryTask);
    }



}
